from django.db import models
from django.contrib.auth.models import User
from codeflow.browser.models import Changeset 
from datetime import datetime
class Review(models.Model):
    CHANGESET_REVIEW = 'changeset'
    REVIEW_PASSED = 'passed'
    REVIEW_FAILED = 'failed'
    author = models.ForeignKey(User) 
    kind = models.CharField(maxlength=30,
                            choices=((CHANGESET_REVIEW, 'Changeset',),))
    status = models.CharField(maxlength=30,
                              choices=(('', 'None'),
                                       (REVIEW_PASSED, 'Passed'),
                                       (REVIEW_FAILED, 'Failed')))
    date = models.DateTimeField(default=datetime.now)
    def passed(self):
        return self.status == Review.REVIEW_PASSED
    def failed(self):
        return self.status == Review.REVIEW_FAILED
    def __str__(self):
        return "Review %s" % self.id
    class Admin:
        pass
    
    
class ChangesetReview(models.Model):
    review = models.ForeignKey(Review, related_name='changeset_reviews',
                               unique=True)
    changeset = models.ForeignKey(Changeset, related_name='reviews')
    def involved_users(self):
        """
        Returns a set of users that has been involved in the review (by creating
        or commenting on it)
        """
        user_ids = set(c.author.id for c in self.comments.all())
        user_ids = user_ids.union(set(c.author.id for c in self.inline_comments.all()))
        user_ids.add(self.review.author.id)
        if self.changeset.scm_user.user is not None:
            user_ids.add(self.changeset.scm_user.user.id)
        return set(User.objects.get(pk=user_id) for user_id in user_ids)
    def first_comment(self):
        "Returns the first general comment made in the review"
        return self.comments.order_by('date')[0]
    class Admin:
        pass

class ChangesetReviewComment(models.Model):
    changeset_review = models.ForeignKey(ChangesetReview, edit_inline=True,
                                         related_name='comments')
    text = models.TextField(core=True)
    author = models.ForeignKey(User, core=True)
    date = models.DateTimeField(default=datetime.now)
    
class InlineChangesetReviewComment(models.Model):
    NEW_REV = 'n'
    OLD_REV = 'o'
    changeset_review = models.ForeignKey(ChangesetReview, edit_inline=True,
                                         related_name='inline_comments')
    file_path = models.CharField(maxlength=512, core=True)
    which_revision = models.CharField(maxlength=1, core=True,
                                      choices = ((NEW_REV, "New"),
                                                 (OLD_REV, "Old")))
    line_number = models.PositiveIntegerField(core=True)
    text = models.TextField(core=True)
    author = models.ForeignKey(User, core=True)
    date = models.DateTimeField(default=datetime.now)



    
    
    
    
    
        
        
    


    

